package com.example.administrator.asynchronoustool;


import android.util.Log;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by FingerMelody on 2016/11/17.
 * **基于Rxjava,RxAndroid, 应用场景：处理比较耗时的操作**
 * 可继续拓展
 */

public class AsynchronousTools {

    private ToDoTimeConsumingListener toDoTimeConsumingListener;
    private MainThreadOperationListener mainListener;
    private String STATE;
    private Subscription subscription;

    public void setMainListener(MainThreadOperationListener mainListener) {
        this.mainListener = mainListener;
    }


    public void setToDoTimeConsumingListener(ToDoTimeConsumingListener toDoTimeConsumingListener) {
        this.toDoTimeConsumingListener = toDoTimeConsumingListener;
    }


    public interface ToDoTimeConsumingListener {
        public void toDoTimeConsuming(String state);


    }

    public interface MainThreadOperationListener {
        public void mainThreadOperation(String state);
    }

    /**
     * 处理比较耗时的操作
     *
     * @param state
     */
    public void toDoTimeConsuming(String state) {
        this.STATE = state;
        subscription = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                toDoTimeConsumingListener.toDoTimeConsuming(STATE);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                mainThreadOperation();
            }
        });


    }

    /**
     * 处理UI 主线程 操作
     */
    public void mainThreadOperation() {
        mainListener.mainThreadOperation(STATE);
    }

    /**
     * **释放**
     * 避免内存泄露的发生
     */
    public void release() {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        } else {
            Log.e("=================", "已经取消订阅");
        }

    }

}
